package org.dromara.tearoom.util;

import java.time.DayOfWeek;
import java.time.LocalDateTime;

/**
 * 星期掩码工具
 * @author CKJ
 * @description: 星期掩码工具
 * @date 2025/6/4 09:46
 */
public class WeekMaskUtils {

    /**
     * 判断当天是否有效
     * @param validDays
     * @return
     */
    public static boolean isNowValid(Integer validDays){
        // 获取当前星期几（1=周一，7=周日）
        DayOfWeek currentDayOfWeek = LocalDateTime.now().getDayOfWeek();
        return isDayValid(validDays,currentDayOfWeek);
    }

    /**
     * 检查某天是否有效
     * @param validDays
     * @param dayOfWeek
     * @return
     */
    public static boolean isDayValid(int validDays, DayOfWeek dayOfWeek) {
        // 转换为位位置（匹配数据库位掩码：周一=0，周日=6）
        int bitPosition = dayOfWeek.getValue() - 1;
        return (validDays & (1 << bitPosition)) == 0;
    }

    /**
     * 位掩码转可读字符串
     * @param validDays
     * @return
     */
    public static String toReadableString(int validDays) {
        String[] days = {"周一", "周二", "周三", "周四", "周五", "周六","周日"};
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 7; i++) {
            if ((validDays & (1 << i)) != 0) {
                sb.append(days[i]).append(",");
            }
        }

        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "无可用日期";
    }

    /**
     * 将星期几转换为位位置（周一=0, 周二=1,..., 周日=6）
     * @param dayOfWeek
     * @return
     */
    public static int convertToBitPosition(int dayOfWeek) {
        // 前端传入：周一=1, 周二=2,...周日=7
        return (dayOfWeek % 7) - 1; // 转换为：周一=0, 周日=6
    }
}
